package comparison;

import java.io.FileNotFoundException;
import java.io.IOException;

import optimizations.SyntaxTreeInterpretter;
import execution.BaseInterpretter;
import execution.Interpretter;
import execution.LoopOptimizedInterpretter;
import execution.Pair;

public class Driver {
	
	private static final int DEFAULT_RUN_COUNT = 1000;
	
	private static void test(Interpretter inter, int repetitions) {
		long sum = 0;
		int successfulRuns = 0;
		for (int i = 0; i < repetitions; i++) {
			long start = System.nanoTime();
			Pair<String, Boolean> ret = inter.compute(System.in);
			long end = System.nanoTime();
			if (ret.getB()) {
				successfulRuns++;
				sum += end-start;
			}
		}
		System.out.println(
				String.format("Completed (%d/%d) repetitions with an average of %f nanoseconds per execution.",
						successfulRuns,
						repetitions,
						((double)sum/successfulRuns)));
	}
	
	public static void main(String[] args) {
		int repetitions = DEFAULT_RUN_COUNT;
		if (args.length >= 1) {
			if (args.length > 1) {
				repetitions = Integer.parseInt(args[0]);
			}
			try {
				System.out.print("Initializing unoptimized interpretter... ");
				final long initializeStart = System.nanoTime();
				BaseInterpretter i1 = new BaseInterpretter(args[0]);
				final long initializeEnd = System.nanoTime();
				System.out.println("Completed in "+(initializeEnd-initializeStart)+" nanoseconds");
				test(i1, repetitions);
			} catch (IOException e) {
				System.out.println("Driver encountered IO Exception!");
			}
			try {
				System.out.print("Initializing loop optimized interpretter... ");
				final long initializeStart = System.nanoTime();
				LoopOptimizedInterpretter i2 = new LoopOptimizedInterpretter(args[0]);
				final long initializeEnd = System.nanoTime();
				System.out.println("Completed in "+(initializeEnd-initializeStart)+" nanoseconds");
				test(i2, repetitions);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				System.out.print("Initializing syntax tree interpretter... ");
				final long initializeStart = System.nanoTime();
				SyntaxTreeInterpretter i3 = new SyntaxTreeInterpretter(args[0]);
				final long initializeEnd = System.nanoTime();
				System.out.println("Completed in "+(initializeEnd-initializeStart)+" nanoseconds");
				test(i3, repetitions);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			System.out.println("At least one argument required: Driver filename [repetitions]");
		}
	}

}
